/**
 * @author 	PrestaLive <contact@prestalive.com>
 * @copyright  2011 PrestaLive
 * @version  	1.0 
 * @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
$(document).ready(function() {
	$('table.tableDnD').tableDnD({
	
		onDragStart: function(table, row) {
			originalOrder = $.tableDnD.serialize();
			reOrder = ':even';
			if (table.tBodies[0].rows[1] && $('#' + table.tBodies[0].rows[1].id).hasClass('alt_row'))
				reOrder = ':odd';
			$('#'+table.id+ '#' + row.id).parent('tr').addClass('myDragClass');
		},
		dragHandle: 'dragHandle',
		onDragClass: 'myDragClass',
		onDrop: function(table, row) {
			if (originalOrder != $.tableDnD.serialize()) {
			
				var way = (originalOrder.indexOf(row.id) < $.tableDnD.serialize().indexOf(row.id))? 1 : 0;
				var ids = row.id.split('_');
				var tableDrag = $('#' + table.id);
				var params = '';
				if (table.id == 'zhelpdesk_ticket_status') {
					params = {
						ajaxStatusPositions: true,
						id_status_parent: ids[1],
						id_status_to_move: ids[2],
						way: way,
						token: token
					};
				}
				if (table.id == 'zhelpdesk_ticket_priority') {
					params = {
						ajaxPriorityPositions: true,
						id_priority_parent: ids[1],
						id_priority_to_move: ids[2],
						way: way,
						token: token
					};
				}
				if (table.id == 'zhelpdesk_ticket_rating') {
					params = {
						ajaxRatingPositions: true,
						id_rating_parent: ids[1],
						id_rating_to_move: ids[2],
						way: way,
						token: token
					};
				}
				
				
				$.ajax({
					type: 'POST',
					async: false,
					url: '../modules/zhelpdesk/zhelpdesk-bf-ajax.php?' + $.tableDnD.serialize(),
					data: params,
					success: function(data) {
						var reg = /_[0-9]$/g;
						tableDrag.find('tbody tr').each(function(i) {
							$(this).attr('id', $(this).attr('id').replace(reg, '_' + i));
							
							// Update link position
							var up_reg  = new RegExp('position=[-]?[0-9]+&');
							
							// Up links
							$(this).find('td.dragHandle a:odd').attr('href', $(this).find('td.dragHandle a:odd').attr('href').replace(up_reg, 'position='+ (i - 1) +'&'));
							
							// Down links
							$(this).find('td.dragHandle a:even').attr('href', $(this).find('td.dragHandle a:even').attr('href').replace(up_reg, 'position='+ (i + 1) +'&'));
							
						});
							
						tableDrag.find('tr').not('.nodrag').removeClass('alt_row');
						tableDrag.find('tr:not(".nodrag"):odd').addClass('alt_row');
						tableDrag.find('tr td.dragHandle a:hidden').show();
						
						if (alternate) {
							tableDrag.find('tr td.dragHandle:first a:odd').hide();
							tableDrag.find('tr td.dragHandle:last a:even').hide();
						}
						else {
							tableDrag.find('tr td.dragHandle:first a:even').hide();
							tableDrag.find('tr td.dragHandle:last a:odd').hide();
						}
					}
				});
			}
		}
	});
})
